package com.yeyaomai.dksns.flowis.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
//import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
import org.apache.log4j.Logger;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import com.yeyaomai.dksns.flowis.dao.DetailDao;
import com.yeyaomai.dksns.flowis.dao.MongoDBBasicDao;
import com.yeyaomai.dksns.flowis.dao.TrendAnalysisHourDao;
import com.yeyaomai.dksns.flowis.domain.TrendAnalysisHour;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisStatDetailDTO;
import com.yeyaomai.dksns.flowis.util.CollectionNames;

/**
 * 每小时处理任务，用于更新PV，独立访客,IP,新独立访客的定时任务
 * 
 * @author xiaqin
 * @date 2012-05-23
 */
public class TrendAnalysisHourExecutor extends
		MongoDBBasicDao<TrendAnalysisHour> {

	@Resource
	private TrendAnalysisHourDao trendAnalysisHourDao;

	@Resource
	private DetailDao detailDao;
	
	final Logger logger = Logger.getLogger("quartz");

	public long countTrendAnalysisDayByTime(String fromTrendDay,
			String toTrendDay) {
		Query query = new Query(Criteria.where("access_date").gte(fromTrendDay)
				.lt(toTrendDay));

		long pvcount = mongoTemplate.count(query, FlowisStatDetailDTO.class);
		return pvcount;
	}

	/**
	 * 定时执行的按小时统计数据
	 * 
	 * @throws ParseException
	 */
	public void saveTrendAnalysisByHour() throws ParseException {
		Date date = new Date();
		SimpleDateFormat mat = new SimpleDateFormat("yyyy-MM-dd HH");
		String exchange = mat.format(date.getTime());
		Date fromdate = mat.parse(exchange);
		Date todate = new Date(fromdate.getTime() - 3600 * 1000);
		String fromTrendDay = mat.format(todate);
		String toTrendDay = exchange;
		int pageview = this.getPageViewByTime(fromTrendDay, toTrendDay);
		int uv = this.getUvByTime(fromTrendDay, toTrendDay);
		int ip = this.getIpByTime(fromTrendDay, toTrendDay);
		int newuv = this.getNewUvByTime(fromTrendDay, toTrendDay);
		SimpleDateFormat formats = new SimpleDateFormat("yyyyMMdd");
		String trendDay = formats.format(date.getTime());

		SimpleDateFormat fmat = new SimpleDateFormat("HH");
		String tohour = fmat.format(date.getTime());
		Calendar dates = Calendar.getInstance();
		dates.add(Calendar.HOUR, -1);
		String beforehour = fmat.format(dates.getTime());
		String hour = beforehour + ":00";
		if (tohour.equals("00")) {
			dates.add(Calendar.DATE, 0);
			trendDay = formats.format(dates.getTime());
		}
		Map<String,String> map = new HashMap<String,String>();
		map.put("currentDay", trendDay);
		map.put("hour", hour);
		TrendAnalysisHour trendHour = trendAnalysisHourDao.getTrendAnalysisHourByDate(map);
		if(null != trendHour)
		{
			trendAnalysisHourDao.delTrendAnalysisHourById(trendHour.getId());
		}
		
		TrendAnalysisHour trendhour = new TrendAnalysisHour();
		trendhour.setTrendDay(formats.parse(trendDay));
		trendhour.setHour(hour);
		trendhour.setPageView(pageview);
		trendhour.setUniqueHost(uv);
		trendhour.setIp(ip);
		trendhour.setNewUniqueHost(newuv);
		logger.info(date+"running saveTrendAnalysisByHour Task add Data 1 count record");
		trendAnalysisHourDao.addTrendAnalysisDay(trendhour);
		logger.info("#############################时间段为"+fromTrendDay+"至"+toTrendDay+"PV数"+pageview+"######################");
		logger.info("#############################趋势分析每小时定时任务执行添加完毕######################");
	}

	/**
	 * 定时任务处理PV
	 */
	private int getPageViewByTime(String fromTrendDay, String toTrendDay) {

		int pvcount = (int) this.countTrendAnalysisDayByTime(
				fromTrendDay, toTrendDay);
		return pvcount;
	}

	/**
	 * 定时任务处理UV
	 */
	private int getUvByTime(String fromTrendDay, String toTrendDay) {
		String mapFunction = "{ cookieId: 0}";
		String reduceFunction = "function(doc, prev) {prev.cookieId+=1}";
		Criteria criteria = Criteria.where("access_date").gte(fromTrendDay).lt(toTrendDay);
		int uvcount = detailDao.group(criteria, CollectionNames.COOKIEID, mapFunction, reduceFunction, FlowisStatDetailDTO.class).getKeys();
		return uvcount;
	}

	/**
	 * 定时任务处理IP
	 */
	private int getIpByTime(String fromTrendDay, String toTrendDay) {
		String mapFunction = "{ip: 0}";
		String reduceFunction = "function(doc, prev) {prev.ip+=1}";
		Criteria criteria = Criteria.where("access_date").gte(fromTrendDay).lt(toTrendDay);
		int ipcount = detailDao.group(criteria, CollectionNames.IP, mapFunction, reduceFunction, FlowisStatDetailDTO.class).getKeys();
		return ipcount;
	}

	/**
	 * 定时任务处理newuv
	 */
	private int getNewUvByTime(String fromTrendDay, String toTrendDay) {
		int newuvcount = 0;
		String mapFunction = "{cookieId: 0}";
		String reduceFunction = "function(doc, prev) {prev.cookieId+=1}";
		Criteria criteria = Criteria.where("access_date").gte(fromTrendDay).lt(toTrendDay).and("visitCount").is(1);
		newuvcount = detailDao.group(criteria, CollectionNames.COOKIEID, mapFunction, reduceFunction, FlowisStatDetailDTO.class).getKeys();
		/*for (FlowisStatDetailDTO engine : result) {
			if (engine.getVisitCount().equals(1)) {
				newuvcount = Integer.valueOf(engine.getCookieId().split("\\.")[0]);
			}
		}*/
		return newuvcount;
	}
}
